/**
 * 登录页面
 */
import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation, Link } from 'react-router-dom';
import {
  Form,
  Input,
  Button,
  Checkbox,
  Card,
  Typography,
  Space,
  Divider,
  Alert,
  Row,
  Col
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  LoginOutlined
} from '@ant-design/icons';
import { useAuth } from '../contexts/AuthContext';
import { useTheme } from '../contexts/ThemeContext';
import { LoginRequest } from '../types/auth';
import { showNotification } from '../utils/notification';

const { Title, Text, Paragraph } = Typography;

const Login: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { state, login, clearError } = useAuth();
  const { currentTheme } = useTheme();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 获取重定向路径
  const from = (location.state as any)?.from?.pathname || '/dashboard';

  useEffect(() => {
    // 如果已经登录，直接跳转
    if (state.isAuthenticated) {
      navigate(from, { replace: true });
    }
  }, [state.isAuthenticated, navigate, from]);

  useEffect(() => {
    // 清除之前的错误
    clearError();
  }, []); // 移除clearError依赖，只在组件挂载时执行一次

  /**
   * 处理登录提交
   */
  const handleSubmit = async (values: LoginRequest) => {
    setLoading(true);
    
    try {
      await login(values);
      showNotification('success', '登录成功', '欢迎回到DataPlexus数据治理平台！');
      navigate(from, { replace: true });
    } catch (error: any) {
      console.error('登录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 演示账户登录
   */
  const handleDemoLogin = (username: string, password: string) => {
    form.setFieldsValue({ username, password, remember_me: false });
    handleSubmit({ username, password, remember_me: false });
  };

  return (
    <div className="login-container">
      {/* 背景装饰 */}
      <div className="login-background">
        <div className="bg-shape shape-1"></div>
        <div className="bg-shape shape-2"></div>
        <div className="bg-shape shape-3"></div>
      </div>

      <div className="login-content">
        <Row justify="center" align="middle" style={{ minHeight: '100vh' }}>
          <Col xs={22} sm={18} md={12} lg={8} xl={6}>
            <Card className="login-card" bordered={false}>
              {/* 系统标题 */}
              <div className="login-header">
                <div className="login-logo">
                  <div className="logo-icon">
                    <span>DP</span>
                  </div>
                </div>
                <Title level={2} className="login-title">
                  DataPlexus
                </Title>
                <Paragraph className="login-subtitle">
                  数据治理平台
                </Paragraph>
              </div>

              {/* 错误提示 */}
              {state.error && (
                <Alert
                  message="登录失败"
                  description={state.error}
                  type="error"
                  showIcon
                  closable
                  onClose={clearError}
                  style={{ marginBottom: 24 }}
                />
              )}

              {/* 登录表单 */}
              <Form
                form={form}
                name="login"
                onFinish={handleSubmit}
                autoComplete="off"
                size="large"
              >
                <Form.Item
                  name="username"
                  rules={[
                    { required: true, message: '请输入用户名或邮箱' },
                    { min: 3, message: '用户名至少3个字符' }
                  ]}
                >
                  <Input
                    prefix={<UserOutlined />}
                    placeholder="用户名或邮箱"
                    autoComplete="username"
                  />
                </Form.Item>

                <Form.Item
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6个字符' }
                  ]}
                >
                  <Input.Password
                    prefix={<LockOutlined />}
                    placeholder="密码"
                    autoComplete="current-password"
                    iconRender={(visible) => 
                      visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
                    }
                  />
                </Form.Item>

                <Form.Item>
                  <Row justify="space-between" align="middle">
                    <Col>
                      <Form.Item name="remember_me" valuePropName="checked" noStyle>
                        <Checkbox>记住我</Checkbox>
                      </Form.Item>
                    </Col>
                    <Col>
                      <Link to="/forgot-password" className="login-forgot">
                        忘记密码？
                      </Link>
                    </Col>
                  </Row>
                </Form.Item>

                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading || state.loading}
                    icon={<LoginOutlined />}
                    block
                    className="login-button"
                  >
                    登录
                  </Button>
                </Form.Item>
              </Form>

              <Divider>
                <Text type="secondary">演示账户</Text>
              </Divider>

              {/* 演示账户 */}
              <div className="demo-accounts">
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Button
                    block
                    onClick={() => handleDemoLogin('admin', 'Admin123!')}
                    className="demo-button"
                  >
                    <Space>
                      <UserOutlined />
                      <span>管理员账户</span>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        (admin / Admin123!)
                      </Text>
                    </Space>
                  </Button>
                  
                  <Button
                    block
                    onClick={() => handleDemoLogin('analyst1', 'Analyst123!')}
                    className="demo-button"
                  >
                    <Space>
                      <UserOutlined />
                      <span>分析师账户</span>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        (analyst1 / Analyst123!)
                      </Text>
                    </Space>
                  </Button>
                  
                  <Button
                    block
                    onClick={() => handleDemoLogin('viewer1', 'Viewer123!')}
                    className="demo-button"
                  >
                    <Space>
                      <UserOutlined />
                      <span>查看者账户</span>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        (viewer1 / Viewer123!)
                      </Text>
                    </Space>
                  </Button>
                </Space>
              </div>

              <Divider />

              {/* 注册链接 */}
              <div className="login-footer">
                <Text type="secondary">
                  还没有账户？
                  <Link to="/register" style={{ marginLeft: 8 }}>
                    立即注册
                  </Link>
                </Text>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default Login;
